<template>
  <div id="cpn-upload-field" :style="{ '--width': width, '--height': height }">
    <el-upload
      class="img-uploader"
      :action="action"
      :show-file-list="false"
      @success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imgData" :src="baseImgDownLoadUrl + imgData" class="img" />
      <template v-else>
        <i v-if="isEmpty(placeholder)" class="el-icon-plus img-uploader-icon"></i>
        <div class="placeholder font4 f12" v-else>{{ placeholder }}</div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';

// 定义 Props 类型
interface UploadFieldProps {
  modelValue?: string;
  width?: string;
  height?: string;
  action?: string;
  placeholder?: string;
}

// 设置 Props 默认值
const props = withDefaults(defineProps<UploadFieldProps>(), {
  modelValue: '',
  width: '120px',
  height: '120px',
  action: `${import.meta.env.VITE_APP_API}/common/upload/img`,
  placeholder: ''
});

const emit = defineEmits<{
  (event: 'update:modelValue', value: string): void;
  (event: 'upload', url: string): void;
}>();

const imgData = ref(props.modelValue);

watch(() => props.modelValue, (newVal) => {
  imgData.value = newVal;
});

const baseImgDownLoadUrl = import.meta.env.VITE_APP_DOWNLOAD_IMG_API

const handleAvatarSuccess = (res: any, file: any) => {
  console.log('res', res, file);
  imgData.value = res.data.url;
  emit('update:modelValue', res.data.url);
  emit('upload', res.data.url);
};

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return (isJPG || isPNG) && isLt2M;
};

const isEmpty = (value: string) => !value || value.trim().length === 0;
</script>

<style lang="scss" scoped>
#cpn-upload-field {
  ::v-deep .img-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #5DCABF !important;
    }
  }

  .placeholder {
    width: var(--width);
    height: var(--height);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  ::v-deep .img-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: var(--width);
    height: var(--height);
    line-height: var(--height);
    text-align: center;
  }

  .img {
    width: var(--width);
    height: var(--height);
    display: block;
  }
}
</style>